from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """添加购物车序列化器"""
    sku_id = serializers.IntegerField()
    count = serializers.IntegerField()
    selected = serializers.BooleanField(default=True)

    def validate(self, attrs):
        sku_id = attrs.get('sku_id')
        # 校验参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return attrs


class CartDeleteSerializer(serializers.Serializer):
    """删除购物车序列化器"""
    sku_id = serializers.IntegerField()

    def validate(self, attrs):
        sku_id = attrs.get('sku_id')
        # 校验参数
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('该商品不存在')
        return attrs


class CartSKUSerializer(serializers.ModelSerializer):
    """查询购物车序列化器"""

    count = serializers.IntegerField()
    selected = serializers.BooleanField(default=True)

    class Meta:
        model = SKU
        fields = ('id', 'count', 'selected', 'name', 'default_image_url', 'price')


class CartSelectAllSerializer(serializers.Serializer):
    """购物车全选序列化器"""
    selected = serializers.BooleanField(label='全选')
